package cn.bonoon.util;

import javax.servlet.http.HttpServletRequest;

import cn.bonoon.kernel.exceptions.ValidateCodeException;
import cn.bonoon.kernel.util.MD5Util;
import cn.bonoon.kernel.util.StringHelper;

public abstract class VerifyCodeHelper {

//	protected final static char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
	//protected final static Color c = new Color(236, 233, 216);
	protected final static String[] VALIDATE_CODES;
	
	static{
		VALIDATE_CODES = new String[] {
				MD5Util.randomMD5String(),
				MD5Util.randomMD5String(),
				MD5Util.randomMD5String(),
				MD5Util.randomMD5String()
		};
	}
	
	public static final String name(Integer type){
		return (null == type || type < 0 || type > VALIDATE_CODES.length) ? VALIDATE_CODES[0] : VALIDATE_CODES[type];
	}
	
	public static final void setCode(HttpServletRequest request, Integer type, String value){
		request.getSession().setAttribute(name(type), value);
	}
	
	public static final void verify(HttpServletRequest request, Integer type, String value){
		if(StringHelper.isEmpty(value)) throw new ValidateCodeException("验证码不能为空！");
		String name = name(type);
		Object cv = request.getSession().getAttribute(name);
		if(null == cv) throw new ValidateCodeException("验证码超时！");
		
		//验证码验证成功后，需要清空该session
		request.getSession().removeAttribute(name);
		
		if(!value.equalsIgnoreCase(cv.toString())) throw new ValidateCodeException("验证码不正确！");
	}
}
